package telex;
/*
 * QueryRunner.java
 *
 * Copyright (c) 2007-2008 Colin Bayer, Douglas Downey, Oren Etzioni,
 *   University of Washington Computer Science and Engineering
 * 
 * See the file "COPYING" in the root directory of this distribution for
 * full licensing information.
 */

public class QueryRunner {

    public QueryRunner(String aDBPath) throws Exception {
        mDB = new Gale1TNGramDatabase(aDBPath, 5);
    }
    private NGramDatabase mDB;

    public boolean run(String aPath) {
        return run(aPath, aPath + ".resolved");
    }

    public boolean run(String aPath, String oPath) {
        IQFReader ir;
        IQFWriter iw;

        try {
            ir = new IQFReader(aPath);
            iw = new IQFWriter(oPath);
        } catch (Exception e) {
            System.out.println("Couldn't open IQF file (" + e + ")");
            return false;
        }

        Query q;
        int n = 0;

        try {
            while ((q = ir.nextQuery()) != null) {
                if (mDB.executeQuery(q) == null) {
                    System.out.println("Failed to execute query " + q + "; halting...");
                    return false;
                }

                //System.out.println("Executed query " + q);

                try {
                    iw.writeQuery(q);
                } catch (Exception e) {
                    System.out.println("Failed to write query (" + e + "); halting...");
                    return false;
                }

                n++;
                if (((double) n / ir.getQueryCount() * 100) % 1
                        < ((double) (n - 1) / ir.getQueryCount() * 100) % 1) {
                    System.out.println((int) ((double) n / ir.getQueryCount() * 100) + "% completed (" + n
                            + " of " + ir.getQueryCount() + " queries).");
                }
            }
            ir.close();
            mDB.closeFiles();
        } catch (Exception e) {
            System.err.println("Couldn't read query from file (" + e + ")");
            return false;
        }

        try {
            iw.finish();
        } catch (Exception e) {
            System.out.println("Failed to finalize output IQF (" + e + "); halting...");
            return false;
        }

        return true;
    }

    public static void main(String[] aArgs) {
        if (aArgs.length < 2) {
            System.out.println("usage: java QueryRunner [input IQF] [n-gram database path]");
            System.exit(255);
        }

        QueryRunner qr = null;

        try {
            qr = new QueryRunner(aArgs[1]);
        } catch (Exception e) {
            System.out.println("Error creating QueryRunner: " + e);
            System.exit(1);
        }

        if (!qr.run(aArgs[0])) {
            System.out.println("Failed to execute queries.  :(");
            System.exit(1);
        } else {
            System.out.println("Query execution successful.  :)");
            return;
        }
    }
}

